<script setup>
import { getStore, setStore, deleteStoreByChunks, getStoreByChunks, setStoreByChunks } from '../services/book-store';
import { getBookDetailsAndChapters, saveBook, getBookSources ,getBookSourceRule, getBookDetails, getBookChapters} from '../services/bookService';
import { ref, onMounted, getCurrentInstance } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { nanoid } from 'nanoid';

const { proxy } = getCurrentInstance();
const router = useRouter();
const bookshelf = ref(getStore('bookshelf') || []);
// 右键菜单状态
const contextMenu = ref({
  visible: false,
  x: 0,
  y: 0,
  currentBook: null
});

// 帮助对话框状态
const helpDialog = ref({
  visible: false
});

// 关闭右键菜单
const closeContextMenu = () => {
  contextMenu.value.visible = false;
};

// 打开帮助对话框
const openHelpDialog = () => {
  helpDialog.value.visible = true;
};

// 关闭帮助对话框
const closeHelpDialog = () => {
  helpDialog.value.visible = false;
};

// 处理右键点击事件
const handleContextMenu = (event, book) => {
  event.preventDefault();
  contextMenu.value = {
    visible: true,
    x: event.clientX,
    y: event.clientY,
    currentBook: book
  };
};

// 处理菜单项点击
const handleMenuClick = async (action) => {
  const book = contextMenu.value.currentBook;
  switch(action) {
    case 'download':
      console.log('下载书籍:', book.title);
      router.push(`/download?id=${book._id}`);
      break;
    case 'delete':
      console.log('删除书籍:', book.title);
      bookshelf.value = bookshelf.value.filter(item => item._id !== book._id);
      setStore('bookshelf', bookshelf.value);
      deleteStoreByChunks(`${book._id}_toc`);
      deleteStoreByChunks(`${book._id}_content`);
      proxy.$toast.success('删除成功');
      break;
    case 'save':
      let bookCacheData = getStoreByChunks(`${book._id}_content`)
      try {
        let path = await saveBook(bookCacheData, book)
        proxy.$toast.success('保存成功');
        window.utools && window.utools.shellShowItemInFolder(path);
      } catch (error) {
        proxy.$toast.success(error);
      }
      break;
    case 'renew':
      let chapters = getStoreByChunks(`${book._id}_toc`);
      try {
        proxy.$toast.info('资源加载中请稍等...');
        let bookSourceRule = getBookSourceRule(book);
        let detail = await getBookDetails(book, bookSourceRule);
        let newChapters = await getBookChapters(detail);
        newChapters = newChapters.map((item, index) => {
          if(chapters[index] && chapters[index].title === item.title) {
            return chapters[index];
          }else{
            return item;
          }
        })
        setStoreByChunks(`${book._id}_toc`, newChapters);
        proxy.$toast.success('更新成功');
      } catch (error) {
        console.log(error);
        proxy.$toast.error('资源加载错误');
      }
      break;
  }
  closeContextMenu();
};

// 导入本地书籍
const importLocalBook = async () => {
  if(!window.utools)return

  let localBookPath = utools.showOpenDialog({
    title: '选择本地书籍',
    properties: ['openFile'],
    filters: [
      { name: 'Book', extensions: ['txt'] }
    ]
  });
  if(!localBookPath || localBookPath.length === 0)return;
  localBookPath = localBookPath[0];
  const bookData = await window.services.readBookFile(localBookPath);

  let { chapters, contents} = await getBookDetailsAndChapters(bookData)
  // console.log();
  
  let _id = nanoid();
  bookshelf.value.unshift({
    _id,
    title: bookData.fileName,
    author: '本地书籍',
    bookType: 0,
  })

  setStore('bookshelf', bookshelf.value);
  setStoreByChunks(`${_id}_toc`, chapters)
  setStoreByChunks(`${_id}_content`, contents)

  
  proxy.$toast.success('导入成功');
};


// 打开阅读器
const openReader = async (book) => {
  if(!book)return;
  bookshelf.value = bookshelf.value.filter(item => item._id !== book._id);
  bookshelf.value.unshift(book);
  setStore('bookshelf', bookshelf.value);
  router.push(`/reader?id=${book._id}`);
};

const openSettingKey = (key) => {
  if(!window.utools)return
  utools.redirectHotKeySetting(key)
}

onMounted(() => {
  // loadBooks();
});
</script>

<template>
  <div class="home" @click="closeContextMenu">
    <div class="book-grid">
      <div 
        v-for="book in bookshelf" 
        :key="book.id"
        class="book-item"
        @click="openReader(book)"
        @contextmenu="handleContextMenu($event, book)"
      >
        <div class="book-cover">
          <img v-if="book.cover" :src="book.cover" :alt="book.title">
          <img v-else src="../assets/book.svg" alt="">
          <div class="book-source">{{ book.sourceName }}</div>
        </div>
        <div class="book-info">
          <div class="book-title" :title="book.title">{{ book.title }}</div>
          <div class="book-author">{{ book.author }}</div>
        </div>
      </div>
      <!-- 导入按钮 -->
      <div class="book-item import-item" @click="importLocalBook">
        <div class="import-content">
          <div class="import-icon">+</div>
          <div class="import-text">导入本地书籍</div>
        </div>
      </div>
    </div>

    <!-- 右键菜单 -->
    <div v-if="contextMenu.visible" 
         class="context-menu"
         :style="{ left: contextMenu.x + 'px', top: contextMenu.y + 'px' }">
      <div v-show="contextMenu.currentBook?.bookType" class="menu-item" @click="handleMenuClick('download')">下载</div>
      <!-- <div class="menu-item" @click="handleMenuClick('catalog')">目录</div>
      <div class="menu-item" @click="handleMenuClick('detail')">详情</div> -->
      <div class="menu-item" @click="handleMenuClick('delete')">删除</div>
      <div class="menu-item" @click="handleMenuClick('save')">保存</div>
      <div v-show="contextMenu.currentBook?.bookType" class="menu-item" @click="handleMenuClick('renew')">更新</div>
    </div>
    
    <!-- 帮助按钮 -->
    <div class="help-button" @click="openHelpDialog">
      <span>?</span>
    </div>
    
    <!-- 帮助对话框 -->
    <div v-if="helpDialog.visible" class="help-dialog-overlay" @click="closeHelpDialog">
      <div class="help-dialog" @click.stop>
        <div class="help-dialog-header">
          <h2>帮助中心</h2>
          <button class="close-button" @click="closeHelpDialog">×</button>
        </div>
        <div class="help-dialog-content">
          <h3>关于听书阅读</h3>
          <p>这是一个简单的电子书听书、阅读应用，支持导入本地TXT格式的电子书。</p>
          
          <h3>基本操作</h3>
          <ul>
            <li><strong>导入</strong>：点击"导入本地书籍"按钮，选择TXT格式的电子书文件。</li>
            <li><strong>阅读</strong>：点击书籍封面即可打开阅读器。阅读页面快捷键 ⬆️⬇️上下滚动，⬅️➡️章节切换 </li>
            <li><strong>听书</strong>：在阅读页面点击界面，弹出工具栏后，右下角进行听书。可通过设置快捷键进行 章节切换、播放/暂停、上句/下句。</li>
            <li><strong>书籍管理</strong>：右键点击书籍封面，可以进行下载、删除、保存(已缓存内容)等操作。</li>
          </ul>
          
          <h3>常见问题</h3>
          <p><strong>Q: 支持哪些格式的电子书？</strong><br>A: 目前仅支持TXT格式的电子书。</p>
          <p><strong>Q: 自定义字体？</strong><br>A: 字体列表为本地电脑字体，可安装电脑字体实现自定义。(安装字体后需对 uTools 进行重启)</p>
          <p><strong>Q: 资源加载错误</strong><br>A: 部分书源稳定性较差，有时可能会无法加载，建议加入书架后进行下载缓存。</p>
          <p><strong>Q: 下载风控？</strong>
            <br>A: 部分网站为防止攻击会有风控防护，频繁请求或高访问频率会对其进行限制(导致加载错误)。
            <br>A: 设置/下载(请求间隔)，请求间隔设置根据情况而定。时间(单位毫秒)
            <br>A: 设置/下载(最大并发)，数值越大下载越快，风险越高，建议数值 1-3
          </p>
          <p><strong>Q: 书源？</strong>
            <br>A: 当前应用对书源规则进行了更改，无法支持第三方书源。如需添加书源，请在评论区留言，作者有时间会对其进行适配
            <br>A: 当前支持的书源较少， 后续会对更多书源进行适配(可能适配较慢请见谅)。
          </p>
          <p><strong>Q: 如何设置快捷键？</strong>
            <br>A: Prev/上一句 <span class="help-span" @click="()=>openSettingKey('Prev')">去设置</span>
            <br>A: Next/下一句 <span class="help-span" @click="()=>openSettingKey('Next')">去设置</span>
            <br>A: PrevChapter/上一章 <span class="help-span" @click="()=>openSettingKey('PrevChapter')">去设置</span>
            <br>A: NextChapter/下一章 <span class="help-span" @click="()=>openSettingKey('NextChapter')">去设置</span>
            <br>A: Play/Pause 播放/暂停 <span class="help-span" @click="()=>openSettingKey('Play/Pause')">去设置</span>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.home {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 54px);
  box-sizing: border-box;
}

h1 {
  margin-bottom: 20px;
}

.import-item {
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border: 2px dashed #d9d9d9;
  transition: all 0.3s;
}

.import-item:hover {
  border-color: #1890ff;
}

.import-content {
  text-align: center;
  color: #666;
}

.import-icon {
  font-size: 32px;
  margin-bottom: 8px;
  color: #1890ff;
}

.import-text {
  font-size: 14px;
}

.book-grid {
  flex: 1;
  overflow-y: auto;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  grid-template-rows: repeat(auto-fill, 210px);
  gap: 20px;
  padding: 16px;
  padding-right: 8px;
}

.book-grid::-webkit-scrollbar {
  width: 6px;
}

/* .book-grid::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
} */

.book-grid::-webkit-scrollbar-track-piece {
  background-color: transparent;
  border-radius: 3px;
}

.book-grid::-webkit-scrollbar-thumb {
  background: rgb(74, 144, 226);
  border-radius: 3px;
  border-color: rgb(74, 144, 226);
}

.book-grid::-webkit-scrollbar-thumb:hover {
  background: rgba(51, 136, 255, 0.8);
}

.book-item {
  width: 120px;
  display: flex;
  flex-direction: column;
  cursor: pointer;
  transition: transform 0.2s;
}

.book-item:hover {
  transform: translateY(-5px);
}

.book-cover {
  height: 150px;
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  position: relative;
}

.book-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.book-cover .book-source {
  position: absolute;
  bottom: 3px;
  right: 3px;
  font-size: 12px;

}

.book-info {
  padding: 10px 0;
}

.book-title {
  font-weight: bold;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.book-author {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.context-menu {
  position: fixed;
  background: #2c3e50;
  border: 1px solid #34495e;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  z-index: 1000;
}

.menu-item {
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.2s;
  color: #ecf0f1;
}

.menu-item:hover {
  background-color: #34495e;
  color: #3498db;
}
/* 帮助按钮样式 */
.help-button {
  position: fixed;
  right: 20px;
  bottom: 20px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: rgb(74, 144, 226);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  transition: all 0.3s;
  z-index: 900;
  font-size: 20px;
  font-weight: bold;
}

.help-button:hover {
  transform: scale(1.1);
  background-color: rgb(51, 136, 255);
}

/* 帮助对话框样式 */
.help-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.help-dialog {
  width: 80%;
  max-width: 600px;
  max-height: 80vh;
  background-color: #2c3e50;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.help-dialog-header {
  padding: 16px 20px;
  border-bottom: 1px solid #34495e;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.help-dialog-header h2 {
  margin: 0;
  color: #ecf0f1;
  font-size: 18px;
}

.close-button {
  background: none;
  border: none;
  color: #ecf0f1;
  font-size: 24px;
  cursor: pointer;
  padding: 0;
  line-height: 1;
}

.help-dialog-content {
  padding: 20px;
  overflow-y: auto;
  color: #ecf0f1;
  flex: 1;
}

.help-dialog-content::-webkit-scrollbar-track-piece{
  background-color: transparent;
}

.help-dialog-content::-webkit-scrollbar-thumb {
  /* background-color: transparent; */
  background: #ecf0f1;
  border-radius: 3px;
  border-color: #ecf0f1;
}

.help-dialog-content h3 {
  margin-top: 20px;
  margin-bottom: 10px;
  color: rgb(74, 144, 226);
}

.help-dialog-content p, .help-dialog-content ul {
  margin-bottom: 15px;
  line-height: 1.5;
}

.help-dialog-content ul {
  padding-left: 20px;
}

.help-dialog-content li {
  margin-bottom: 8px;
}

.help-dialog-content strong {
  color: rgb(74, 144, 226);
}

.help-span{
  color: #1890ff;
  cursor: pointer;
}
</style>